<template>
    <div class="chart-wrapper">
        <BaseChart height="100%" :options="chartOption" />
    </div>
</template>

<script setup>
import { computed } from 'vue'
import { useReportStore } from '@/stores/report'
import { useI18n } from 'vue-i18n'
import BaseChart from '@/components/chart/BaseChart.vue'

const { t } = useI18n()
const reportStore = useReportStore()
const props = defineProps({
    chartType: {
        type: String,
        default: 'bar'
    }
})

const getWeekDayName = (dateStr) => {
    const weekDays = [
        t('date.week[0]'),
        t('date.week[1]'),
        t('date.week[2]'),
        t('date.week[3]'),
        t('date.week[4]'),
        t('date.week[5]'),
        t('date.week[6]')
    ]
    const date = new Date(dateStr)
    return weekDays[date.getDay()]
}

const formatChartData = (data) => {
    if (!data?.data?.length) return []
    return data.data.map(item => ({
        time: getWeekDayName(item.start_time),
        value: Number(item.Value || 0).toFixed(2)
    }))
}

const chartOption = computed(() => {
    const currentWeekData = reportStore.fourWeekData[0]
    const week1Data = reportStore.fourWeekData[1]
    const week2Data = reportStore.fourWeekData[2]
    const week3Data = reportStore.fourWeekData[3]

    const formattedCurrentWeek = formatChartData(currentWeekData)
    const formattedWeek1 = formatChartData(week1Data)
    const formattedWeek2 = formatChartData(week2Data)
    const formattedWeek3 = formatChartData(week3Data)

    if (!formattedCurrentWeek.length && !formattedWeek1.length &&
        !formattedWeek2.length && !formattedWeek3.length) return null

    return {
        title: t('date.title.weekly'),
        xAxisData: formattedCurrentWeek.map(item => item.time),
        series: [
            {
                name: t('date.label.threeWeeksAgo'),
                data: formattedWeek3.map(item => item.value),
                type: props.chartType,
                showExtremum: true
            },
            {
                name: t('date.label.twoWeeksAgo'),
                data: formattedWeek2.map(item => item.value),
                type: props.chartType,
                showExtremum: true
            },
            {
                name: t('date.label.lastWeek'),
                data: formattedWeek1.map(item => item.value),
                type: props.chartType,
                showExtremum: true
            },
            {
                name: t('date.label.thisWeek'),
                data: formattedCurrentWeek.map(item => item.value),
                type: props.chartType,
                showExtremum: true
            }
        ],
        showMarkLine: true,
        showZoom: false
    }
})
</script>